package com.blue.gateway.config.filters.global;

import cn.hutool.http.HttpStatus;
import com.alibaba.fastjson.JSON;
import com.blue.common.exception.BaseException;
import com.blue.gateway.bean.constants.GatewayHeaderKey;
import com.blue.gateway.jwt.JwtTokenUtil;
import com.blue.user.model.entity.SysLoginUserInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;

import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

/**
 * 5.Token校验过滤器
 *
 * @author liulei
 * @version 1.0
 */
@Slf4j
@Configuration
public class JwtTokenVerifyFilter extends AbstractGatewayFilter implements GlobalFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        log.info("5.过滤器链-jwt校验处理，对token进行校验");
        if (this.isIgnoreUrl(exchange)) {
            log.info("该请求属于忽略类型url，此处不检测token");
            return chain.filter(exchange);
        }
        String token = exchange.getRequest().getHeaders().getFirst(GatewayHeaderKey.TOKEN);
        if (StringUtils.isEmpty(token)) {
            throw new BaseException(HttpStatus.HTTP_BAD_REQUEST, "请求格式错误，请检查token");
        }
        // TODO 根据scope的值，再根据每个系统的特性，解析token
        SysLoginUserInfo jwtPayLoad = JwtTokenUtil.getJwtPayLoad(token);
        log.info("token信息为:[{}],[{}]", token, JSON.toJSONString(jwtPayLoad));
        // 解析token后添加相关header信息
        ServerHttpRequest serverHttpRequest = exchange.getRequest().mutate()
                .header(GatewayHeaderKey.TOKEN, token)
                .header(GatewayHeaderKey.USER_INFO, encoder.encodeToString(JSON.toJSONString(jwtPayLoad).getBytes(StandardCharsets.UTF_8)))
                .build();
        return chain.filter(exchange.mutate().request(serverHttpRequest).build());
    }

    @Override
    public int getOrder() {
        return -60;
    }

}
